package com.tt.fashionWebSite.dao.jpa;

import com.tt.fashionWebSite.dao.ChiTietHoaDonDao;
import com.tt.fashionWebSite.domain.ChiTietDatHang;
import com.tt.fashionWebSite.domain.ChiTietHoaDon;
import com.tt.fashionWebSite.domain.HoaDon;
import com.tt.fashionWebSite.dto.ChiTietHoaDonDto;
import com.tt.fashionWebSite.dto.ChiTietHoaDonFullDto;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by PC on 11/28/14.
 */
@Repository("chiTietHoaDon")
public class ChiTietHoaDonJpaDao extends GenericJpaDao<ChiTietHoaDon, String> implements ChiTietHoaDonDao {
    public ChiTietHoaDonJpaDao () {
        super(ChiTietHoaDon.class);
    }

    @Override
    public List<ChiTietHoaDon> getBillDetailCommon(){
        return getEntityManager().createNamedQuery(ChiTietHoaDon.GET_BILLDETAIL_ALL, ChiTietHoaDon.class).getResultList();
//        String sql = "SELECT c FROM ChiTietHoaDon c  ORDER BY c.hoaDon.maHD DESC";
//        return getEntityManager().createQuery(sql, ChiTietHoaDon.class).getResultList();
    }

    @Override
    public List<ChiTietHoaDon> getBillDetailInfoDelete(List<ChiTietHoaDonDto> listBill){
        String sql = "DELETE c FROM ChiTietHoaDon c  Where c.maHD IN (" +listBill+ ")";
        return getEntityManager().createQuery(sql, ChiTietHoaDon.class).getResultList();
//        return getEntityManager().createNamedQuery(HoaDon.GET_BILL_ALL_TEST, HoaDon.class)
//                .getResultList();
    }

    @Override
    public List<ChiTietHoaDonFullDto> getBillDetailByIdBill(String idBill) {
        String strQuery = "SELECT "
              + "c.MA_CT_SP, "
              + "c.MA_HD "
              + "FROM chi_tiet_hd c "
              + "JOIN hoa_don h "
              + "ON h.MA_HD = c.MA_HD "
              + "WHERE c.MA_HD  = :idBill ";

        Query query = getEntityManager().createNativeQuery(strQuery);
        query.setParameter("idBill", idBill);

        List<Object> results = query.getResultList();
        List<ChiTietHoaDonFullDto> chiTietHoaDonFullDtos = new ArrayList<ChiTietHoaDonFullDto>();
        ChiTietHoaDonFullDto chiTietHoaDonFullDto = null;
        for (int i = 0; i < results.size(); i++) {
            Object[] userDB = (Object[]) results.get(i);
            chiTietHoaDonFullDto = new ChiTietHoaDonFullDto(userDB);
            chiTietHoaDonFullDtos.add(chiTietHoaDonFullDto);
        }
        return chiTietHoaDonFullDtos;
    }

    @Override
    public void deleteBill(String idBill) {
        Query q1 = getEntityManager().createQuery("DELETE FROM ChiTietHoaDon c WHERE c.hoaDon.maHD = :idBill ");
        q1.setParameter("idBill", idBill);
        q1.executeUpdate();
    }
}
